package com.swan.security.security;

import com.alibaba.fastjson.JSONObject;
import com.swan.security.cache.ITokenCache;
import com.swan.security.token.JwtTokenManager;
import com.swan.web.domain.BaseResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

/** Logout 处理。<br/>
 * 1. 不需要自己自己定义 logout 接口 <br/>
 * 2. 需要手动清理 token 缓存
 * @author zongf
 * @date 2025-02-20
 **/
public class SecurityLogoutHandler implements LogoutSuccessHandler {

    @Autowired
    private ITokenCache tokenCache;

    @Autowired
    private JwtTokenManager jwtTokenManager;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = this.jwtTokenManager.resolveToken(request);

        // 删除 token
        if(token != null){
            this.tokenCache.remove(token);
        }

        // 写入
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JSONObject.toJSONString(BaseResponse.success()));

    }
}
